#include <jni.h>
#include <string>
#include "FFPlayer.h"
JavaCallHelper *helper;  //java的反射
FFPlayer *ffPlayer;      //播放器
FFStatus *ffStatus;
JavaVM *javaVm;
extern "C"


#define PLAY_MODEL_DEFAULT  1
#define PLAY_MODEL_FRAME_PREVIEW  2
extern "C"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved){
    jint result = -1;
    javaVm = vm;
    JNIEnv *env;

    if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) {
        LOGE("ERROR: GetEnv failed\n");
        return result;
    }
    return JNI_VERSION_1_6;

}

extern "C"
JNIEXPORT void JNICALL
Java_com_yesemate_splayer_Splayer_n_1palymodel(JNIEnv *env, jobject thiz, jint model) {
    if (ffPlayer!= nullptr){
        if (model==PLAY_MODEL_FRAME_PREVIEW){
            ffPlayer->setIsFramePreview(true);
        }else{
            ffPlayer->setIsFramePreview(true);
        }
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_yesemate_splayer_Splayer_n_1parpared(JNIEnv *env, jobject thiz, jstring source) {
    const char *url = env->GetStringUTFChars(source, 0);
    if (ffPlayer== nullptr) {
        if (helper == nullptr) {
            helper = new JavaCallHelper(javaVm, env, thiz);
        }

        if (ffStatus == nullptr) {
            ffStatus = new FFStatus();
        }
//
        ffPlayer = new FFPlayer(helper, url, ffStatus);
        ffPlayer->prepared();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_yesemate_splayer_Splayer_n_1init_1frame_1by_1ffmepg(JNIEnv *env, jobject thiz,
                                                             jstring source) {
    if (helper == NULL){
        helper = new JavaCallHelper(javaVm,env,thiz);
    }
    if (ffStatus == NULL){
        ffStatus = new FFStatus();
    }
}

void *startCallBack(void *data)
{
    FFPlayer *fFmpeg = static_cast<FFPlayer *>(data);
    fFmpeg->start();
    return nullptr;
}
pthread_t thread_start;
extern "C"
JNIEXPORT void JNICALL
Java_com_yesemate_splayer_Splayer_n_1play(JNIEnv *env, jobject thiz, jint model) {
    if (ffPlayer != NULL){
        pthread_create(&thread_start, NULL, startCallBack, ffPlayer);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yesemate_splayer_Splayer_n_1volume(JNIEnv *env, jobject thiz, jint vol) {
    if (ffPlayer != NULL){
        ffPlayer->setVolume(vol);
    }
}